﻿import { useState, useRef, useEffect } from "react"
import { usePersistentState } from "./utils/hooks"
import ScreenshotTab from "./components/ScreenshotTab"
import EditorTab from "./components/EditorTab"
import TimerTab from "./components/TimerTab"
import RecordingTab from "./components/RecordingTab"

// 插件状态接口
interface PluginState {
  isActive: boolean
  activeTabs: number[]
  startTime: number
  lastActivity: number
  totalSessions: number
  sessionId: string
}

function IndexPopup() {
  // 使用持久化状态管理活跃标签页
  const {
    state: activeTab,
    setState: setActiveTab,
    persistState: saveActiveTab
  } = usePersistentState<'screenshot' | 'editor' | 'timer' | 'recording'>('activeTab', 'screenshot')

  const [pluginState, setPluginState] = useState<PluginState | null>(null)
  const [isConnected, setIsConnected] = useState(false)
  const [connectionAttempts, setConnectionAttempts] = useState(0)
  const editorRef = useRef<HTMLDivElement>(null)

  // 向后台脚本发送消息
  const sendToBackground = async (message: any) => {
    try {
      return await chrome.runtime.sendMessage(message)
    } catch (error) {
      console.error("发送消息到后台脚本失败:", error)
      return null
    }
  }

  // 获取插件状态
  const getPluginState = async () => {
    try {
      const state = await sendToBackground({ type: "GET_PLUGIN_STATE" })
      if (state) {
        setPluginState(state)
        setIsConnected(true)
        setConnectionAttempts(0)
        console.log(" 成功获取插件状态:", state)
      } else {
        setIsConnected(false)
        setConnectionAttempts(prev => prev + 1)
        console.log(" 获取插件状态失败")
      }
    } catch (error) {
      setIsConnected(false)
      setConnectionAttempts(prev => prev + 1)
      console.error("获取插件状态出错:", error)
    }
  }

  // 重置会话
  const resetSession = async () => {
    try {
      const response = await sendToBackground({ type: "RESET_SESSION" })
      if (response?.success) {
        console.log(" 会话已重置:", response.sessionId)
        await getPluginState()
      }
    } catch (error) {
      console.error("重置会话失败:", error)
    }
  }

  // 向所有标签页广播消息
  const broadcastToAllTabs = async (message: string, type: string = "info") => {
    try {
      await sendToBackground({
        type: "BROADCAST_TO_ALL",
        data: {
          type: "BROADCAST_MESSAGE",
          data: {
            message,
            type,
            timestamp: Date.now()
          }
        }
      })
      console.log(" 广播消息已发送")
    } catch (error) {
      console.error("广播消息失败:", error)
    }
  }

  // 执行插件命令
  const executePluginCommand = async (command: string, data: any = {}) => {
    try {
      await sendToBackground({
        type: "BROADCAST_TO_ALL",
        data: {
          type: "PLUGIN_COMMAND",
          command,
          data
        }
      })
      console.log(" 插件命令已执行")
    } catch (error) {
      console.error("执行插件命令失败:", error)
    }
  }

  // 处理标签页切换
  const handleTabChange = async (tab: 'screenshot' | 'editor' | 'timer' | 'recording') => {
    setActiveTab(tab)
    await saveActiveTab(tab)
  }

  // 组件挂载时获取插件状态
  useEffect(() => {
    console.log(" Popup 组件初始化")
    
    // 立即获取状态
    getPluginState()
    
    // 定期更新状态
    const interval = setInterval(() => {
      getPluginState()
    }, 3000) // 每3秒检查一次
    
    // 如果连接失败，增加重试频率
    const retryInterval = setInterval(() => {
      if (!isConnected && connectionAttempts < 10) {
        console.log(` 尝试重新连接 (${connectionAttempts + 1}/10)`)
        getPluginState()
      }
    }, 2000) // 每2秒重试一次
    
    return () => {
      clearInterval(interval)
      clearInterval(retryInterval)
    }
  }, [isConnected, connectionAttempts])

  // 插入图片到编辑器的通用函数
  const insertImageToEditor = (imageSrc: string, altText: string = '图片') => {
    if (!editorRef.current) return

    // 确保编辑器获得焦点
    editorRef.current.focus()

    // 创建图片元素
    const img = document.createElement('img')
    img.src = imageSrc
    img.alt = altText
    img.style.maxWidth = '100%'
    img.style.height = 'auto'
    img.style.display = 'block'
    img.style.margin = '8px 0'
    img.style.borderRadius = '4px'
    img.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'

    // 获取当前光标位置
    const selection = window.getSelection()
    if (selection && selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      range.deleteContents()
      range.insertNode(img)
      
      // 将光标移到图片后面
      range.setStartAfter(img)
      range.setEndAfter(img)
      selection.removeAllRanges()
      selection.addRange(range)
    } else {
      // 如果没有选择，直接添加到编辑器末尾
      editorRef.current.appendChild(img)
      
      // 添加换行
      const br = document.createElement('br')
      editorRef.current.appendChild(br)
    }
  }

  // 格式化时间显示
  const formatTime = (milliseconds: number): string => {
    const seconds = Math.floor(milliseconds / 1000)
    const minutes = Math.floor(seconds / 60)
    const hours = Math.floor(minutes / 60)
    
    if (hours > 0) {
      return `${hours}h ${minutes % 60}m ${seconds % 60}s`
    } else if (minutes > 0) {
      return `${minutes}m ${seconds % 60}s`
    } else {
      return `${seconds}s`
    }
  }

  return (
    <div
      style={{
        padding: 16,
        width: 400,
        minHeight: 300,
        fontFamily: "Arial, sans-serif"
      }}>
      
      {/* 全局状态指示器 */}
      <div style={{
        padding: "8px 12px",
        backgroundColor: isConnected ? "#d4edda" : "#f8d7da",
        color: isConnected ? "#155724" : "#721c24",
        borderRadius: "4px",
        marginBottom: "12px",
        fontSize: "12px",
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center"
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
          <div style={{
            width: "8px",
            height: "8px",
            borderRadius: "50%",
            backgroundColor: isConnected ? "#28a745" : "#dc3545",
            animation: isConnected ? "pulse 2s infinite" : "none"
          }}></div>
          <span>{isConnected ? "插件活跃" : "连接断开"}</span>
          {!isConnected && connectionAttempts > 0 && (
            <span style={{ fontSize: "10px", opacity: 0.7 }}>
              (重试 {connectionAttempts}/10)
            </span>
          )}
        </div>
        {pluginState && (
          <div style={{ fontSize: "11px", opacity: 0.8 }}>
            {pluginState.activeTabs.length} 标签页 | {formatTime(Date.now() - pluginState.startTime)}
          </div>
        )}
      </div>

      {/* 连接状态详情 */}
      {pluginState && (
        <div style={{
          padding: "6px 8px",
          backgroundColor: "#e7f3ff",
          borderRadius: "4px",
          marginBottom: "8px",
          fontSize: "11px",
          color: "#0066cc"
        }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <span>会话ID: {pluginState.sessionId}</span>
            <span>总会话: {pluginState.totalSessions}</span>
          </div>
        </div>
      )}

      {/* 全局控制按钮 */}
      <div style={{
        display: "flex",
        gap: "6px",
        marginBottom: "12px"
      }}>
        <button
          onClick={() => broadcastToAllTabs("这是一条来自插件的广播消息！", "broadcast")}
          disabled={!isConnected}
          style={{
            flex: 1,
            padding: "6px 8px",
            backgroundColor: isConnected ? "#6f42c1" : "#ccc",
            color: "white",
            border: "none",
            borderRadius: "4px",
            fontSize: "11px",
            cursor: isConnected ? "pointer" : "not-allowed"
          }}>
           广播消息
        </button>
        <button
          onClick={() => executePluginCommand("SHOW_NOTIFICATION", { message: "插件命令测试", type: "success" })}
          disabled={!isConnected}
          style={{
            flex: 1,
            padding: "6px 8px",
            backgroundColor: isConnected ? "#28a745" : "#ccc",
            color: "white",
            border: "none",
            borderRadius: "4px",
            fontSize: "11px",
            cursor: isConnected ? "pointer" : "not-allowed"
          }}>
           测试命令
        </button>
        <button
          onClick={getPluginState}
          style={{
            flex: 1,
            padding: "6px 8px",
            backgroundColor: "#17a2b8",
            color: "white",
            border: "none",
            borderRadius: "4px",
            fontSize: "11px",
            cursor: "pointer"
          }}>
           刷新状态
        </button>
      </div>

      {/* 重置会话按钮 */}
      <div style={{ marginBottom: "12px" }}>
        <button
          onClick={resetSession}
          disabled={!isConnected}
          style={{
            width: "100%",
            padding: "6px 8px",
            backgroundColor: isConnected ? "#ffc107" : "#ccc",
            color: isConnected ? "#000" : "#666",
            border: "none",
            borderRadius: "4px",
            fontSize: "11px",
            cursor: isConnected ? "pointer" : "not-allowed"
          }}>
           重置会话
        </button>
      </div>
      
      {/* 标签页切换 */}
      <div style={{ 
        display: 'flex', 
        marginBottom: 16, 
        borderBottom: '1px solid #ddd' 
      }}>
        <button
          onClick={() => handleTabChange('screenshot')}
          style={{
            flex: 1,
            padding: '6px 8px',
            backgroundColor: activeTab === 'screenshot' ? '#007bff' : 'transparent',
            color: activeTab === 'screenshot' ? 'white' : '#333',
            border: 'none',
            borderBottom: activeTab === 'screenshot' ? '2px solid #007bff' : '2px solid transparent',
            cursor: 'pointer',
            fontSize: '12px'
          }}>
           截屏
        </button>
        <button
          onClick={() => handleTabChange('recording')}
          style={{
            flex: 1,
            padding: '6px 8px',
            backgroundColor: activeTab === 'recording' ? '#007bff' : 'transparent',
            color: activeTab === 'recording' ? 'white' : '#333',
            border: 'none',
            borderBottom: activeTab === 'recording' ? '2px solid #007bff' : '2px solid transparent',
            cursor: 'pointer',
            fontSize: '12px'
          }}>
           录屏
        </button>
        <button
          onClick={() => handleTabChange('editor')}
          style={{
            flex: 1,
            padding: '6px 8px',
            backgroundColor: activeTab === 'editor' ? '#007bff' : 'transparent',
            color: activeTab === 'editor' ? 'white' : '#333',
            border: 'none',
            borderBottom: activeTab === 'editor' ? '2px solid #007bff' : '2px solid transparent',
            cursor: 'pointer',
            fontSize: '12px'
          }}>
           编辑器
        </button>
        <button
          onClick={() => handleTabChange('timer')}
          style={{
            flex: 1,
            padding: '6px 8px',
            backgroundColor: activeTab === 'timer' ? '#007bff' : 'transparent',
            color: activeTab === 'timer' ? 'white' : '#333',
            border: 'none',
            borderBottom: activeTab === 'timer' ? '2px solid #007bff' : '2px solid transparent',
            cursor: 'pointer',
            fontSize: '12px'
          }}>
           定时器
        </button>
      </div>

      {/* 截屏标签页 */}
      {activeTab === 'screenshot' && (
        <ScreenshotTab onInsertToEditor={insertImageToEditor} />
      )}

      {/* 录屏标签页 */}
      {activeTab === 'recording' && (
        <RecordingTab onInsertToEditor={insertImageToEditor} />
      )}

      {/* 富文本编辑器标签页 */}
      {activeTab === 'editor' && (
        <div>
          <EditorTab />
          {/* 隐藏的编辑器引用，用于插入图片 */}
          <div
            ref={editorRef}
            style={{ display: 'none' }}
          />
        </div>
      )}

      {/* 定时器标签页 */}
      {activeTab === 'timer' && (
        <TimerTab />
      )}

      {/* 添加脉冲动画样式 */}
      <style>{`
        @keyframes pulse {
          0% { opacity: 1; }
          50% { opacity: 0.5; }
          100% { opacity: 1; }
        }
      `}</style>
    </div>
  )
}

export default IndexPopup
